package com.station.Activitys.http;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.IOException;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * 项目名称：车管所 手机app
 * 类描述：网络请求管理类(单例模式)
 * 创建人：张飞祥
 * 创建时间：2018/04/18 下午2:17
 * 修改人：张飞祥
 * 修改时间：2018/04/18 下午2:17
 * 修改备注：
 */
public class NetWorkMgr {

    private static File baseDir = null;
    private final int HTTP_RESPONSE_DISK_CACHE_MAX_SIZE = 10 * 1024 * 1024;

    private static class NetWorkMgrHolder {
        private static final NetWorkMgr INSTANCE = new NetWorkMgr();
    }


    private NetWorkMgr() {}


    public static final NetWorkMgr getInstance(Context context) {
        baseDir = context.getCacheDir();
        return NetWorkMgrHolder.INSTANCE;
    }


    public synchronized <T> T getServiceAPI(Class<T> clazz) {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(HttpConstant.hTTP_URl).addCallAdapterFactory(RxJavaCallAdapterFactory
                        .create())
                        // 使用RxJava作为回调适配器
                .addConverterFactory(GsonConverterFactory
                        .create()) // 使用Gson作为数据转换器
                .client(getCustomOkhttp()).build();

        return retrofit.create(clazz);
    }


    /**** 自定义一些okhttp的配置 */
    private OkHttpClient getCustomOkhttp() {
        File cacheDir = null;
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
        if (baseDir != null) {
            //配置okhttp 缓存机制
            cacheDir = new File(baseDir, "HttpResponseCache");
        }
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder().
                addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        long t1 = System.nanoTime();
                        //Log.i(NetWorkMgr.class.getSimpleName(), String
                        //        .format("Sending request %s on %s%n%s", request
                        //                .url(), chain.connection(), request
                        //                .headers()));
                        //在这里产生一个响应应答请求。
                        Response response = chain.proceed(request);

                        long t2 = System.nanoTime();

                        Log.i(NetWorkMgr.class.getSimpleName(), String
                                .format("Received response for %s in %.1fms%n%s", response
                                                .request().url(),
                                        (t2 - t1) / 1e6d, response.headers()));
                        //缓存设置 max-age= 60 （60秒内无论有无网络都读取缓存）
                        //max-stale=2419200  (无网络情况下将缓存保存四周)
                        String cacheControl = request.cacheControl().toString();

                        if (TextUtils.isEmpty(cacheControl)) {
                            cacheControl = "public, max-age=60 ,max-stale=2419200";
                        }
                        return response.newBuilder()
                                       .header("Cache-Control", cacheControl)
                                       .removeHeader("Pragma").build();
                    }
                })

                                                      .addInterceptor(loggingInterceptor)
                                                      .cache(new Cache(cacheDir, HTTP_RESPONSE_DISK_CACHE_MAX_SIZE))
                                                      .build();

        return okHttpClient;
    }
}